<template>
    <div>
        <div class="page-container">
            <el-backtop :right="100" :bottom="100" ref="refBackTop" :visibility-height="100" target=".el-main"></el-backtop>
            <!-- 头部过滤部分 -->
            <div class="page-filter">
                <el-input v-model="filterGroupShop.spuName" placeholder="请输入商品名称" />
                <el-input v-model="filterGroupShop.id" placeholder="请输入团购ID" />
                <el-select v-model="filterGroupShop.status" placeholder="请选择团购状态">
                    <el-option v-for="item in filterStatus" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
                <el-button :icon="Search" type="primary" @click="getGroupShop">查找</el-button>
                <el-button :icon="Plus" type="primary" @click="handleAddOpenDialog">添加</el-button>
            </div>
            <div class="page-table">
                <el-table :data="groupShopList" border style="width: 100%" v-loading="loading"
                    element-loading-text="拼命加载中...">
                    <el-table-column type="expand">
                        <template #default="props">
                            <table border="1" cellpadding="0" cellspacing="0" style="width: 100%;border-right: 0;"
                                class="in-table">
                                <tr>
                                    <td style="width: 80px;">类目ID</td>
                                    <td style="border-right: 0;">{{ props.row.categoryId }}</td>
                                </tr>
                                <tr>
                                    <td>sky商品属性</td>
                                    <td style="padding:10px;border-right: 0;padding-right: 0;">
                                        <div m="4">
                                            <el-table :data="props.row.groupShopSkuDTOList" border>
                                                <el-table-column label="SkuId" prop="skuId" width="80" />
                                                <el-table-column label="规格标题" prop="title" />
                                                <el-table-column label="团购价格(元)" prop="skuGroupShopPrice" />
                                                <el-table-column label="库存" prop="stock" width="80" />
                                                <el-table-column label="原始价格(元)" prop="originalPrice" />
                                                <el-table-column label="售卖价格(元)" prop="price" />
                                                <el-table-column label="会员价格(元)" prop="vipPrice" />
                                                <el-table-column label="国际条码" prop="barCode" />
                                            </el-table>
                                        </div>
                                    </td>
                                </tr>
                            </table>

                        </template>
                    </el-table-column>
                    <el-table-column label="团购ID" prop="id" align="center" width="70" />
                    <el-table-column label="商品ID" prop="spuId" align="center" />
                    <el-table-column label="商品名称" prop="title" align="center" />
                    <el-table-column label="商品主题" align="center" width="70">
                        <template #default="scope">
                            <el-popover placement="right" :width="225" trigger="hover">
                                <template #reference>
                                    <el-image :src="scope.row.img" style="width: 50px;height:50px"></el-image>
                                </template>
                                <el-image :src="scope.row.img" style="width: 200px;height:200px"></el-image>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="未满策略" align="center" width="90">
                        <template #default="scope">
                            <el-tag type="warning" v-if="scope.row.automaticRefund === 1">发货</el-tag>
                            <el-tag type="success" v-else>退款</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="活动状态" align="center" width="90">
                        <template #default="scope">
                            <el-tag v-if="scope.row.status === 1">激活</el-tag>
                            <el-tag type="danger" v-else>冻结</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="开始时间" align="center">
                        <template #default="scope">
                            {{ moment(scope.row.gmtStart).format('YYYY-MM-DD hh:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="结束时间" align="center">
                        <template #default="scope">
                            {{ moment(scope.row.gmtEnd).format('YYYY-MM-DD hh:mm:ss') }}
                        </template>
                    </el-table-column>
                    <el-table-column label="当前人数" prop="buyerNum" align="center" width="70" />
                    <el-table-column label="目标人数" prop="minNum" align="center" width="70" />
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button type="primary" @click="handleEdit(scope.row)"
                                v-if="scope.row.status == 0">编辑</el-button>
                            <el-button type="danger" @click="handleDelete(scope.row.id)"
                                v-if="scope.row.status == 0">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div style="overflow: hidden;">
                <Pagination v-bind="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <el-drawer ref="drawerRef" v-model="dialog" direction="ltr" @close="handleCloseDialog" @open="refresh++"
                :show-close="false">
                <!-- 抽屉头部 -->
                <template #header>
                    <span>{{ dialogName }}团购商品</span>
                    <div>
                        <el-button @click="handleCancel">取消</el-button>
                        <el-button type="primary" @click="handleSubmit(ruleFormRef)">{{ dialogName }}</el-button>
                    </div>
                </template>
                <!-- 抽屉主题部分 -->
                <div class="dialog-content">
                    <div class="shop-attribute">
                        <span class="title-span">商品属性(spu)</span>
                        <div>
                            <el-form :model="dataForm" label-width="150px" ref="ruleFormRef" :rules="rules"
                                hide-required-asterisk>
                                <el-form-item label="团购商品" prop="spuId">
                                    <el-cascader v-model="dataForm.spuId" :options="spuBigTree" @change="handleChangeShop"
                                        :key="refresh" :props="{ emitPath: false, value: 'id' }" placeholder="请选择商品"
                                        filterable clearable />
                                </el-form-item>
                                <el-form-item label="团购时间">
                                    <el-col :span="11">
                                        <el-form-item prop="gmtStart">
                                            <el-date-picker v-model="dataForm.gmtStart" type="datetime"
                                                placeholder="请选择起始时间" style="width: 100%" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col class="text-center" :span="2">
                                        <span style="margin: 0 10px;">至</span>
                                    </el-col>
                                    <el-col :span="11">
                                        <el-form-item prop="gmtEnd">
                                            <el-date-picker v-model="dataForm.gmtEnd" type="datetime" placeholder="请选择结束时间"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="团购基础人数" prop="minNum">
                                    <el-input-number v-model="dataForm.minNum" :min="1" controls-position="right" />
                                </el-form-item>
                                <el-form-item label="活动结束时人数没有达到基础人数采用" prop="automaticRefund">
                                    <div style="margin-top: 20px">
                                        <el-radio-group v-model="dataForm.automaticRefund">
                                            <el-radio-button :label="1">不退款，我要发货</el-radio-button>
                                            <el-radio-button :label="0">自动退款，不发货</el-radio-button>
                                        </el-radio-group>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                    <!-- 抽屉商品类型 -->
                    <div class="shop-type">
                        <el-card class="box-card">
                            <template #header>
                                <div class="card-header">
                                    <span class="title-span">商品类型(sku)</span>
                                    <el-popover placement="right" :width="300" trigger="click">
                                        <template #reference>
                                            <el-button type="primary" ref="refButton"
                                                :disabled="!dataForm.groupShopSkuList.length">批量定价</el-button>
                                        </template>
                                        <div>
                                            <el-row :gutter="0">
                                                <el-col :span="7">
                                                    <span style="line-height: 32px;">团购价格</span>
                                                </el-col>
                                                <el-col :span="14">
                                                    <el-input-number :min="1" controls-position="right"
                                                        v-model="morePrice" />
                                                </el-col>
                                            </el-row>
                                            <el-row :gutter="0" style="margin-top:20px">
                                                <el-col :span="7">
                                                    <span></span>
                                                </el-col>
                                                <el-col :span="14">
                                                    <el-button @click="refButton.$el.click?.()">取消</el-button>
                                                    <el-button type="primary" @click="handleMorePrice">确定</el-button>
                                                </el-col>
                                            </el-row>
                                        </div>
                                    </el-popover>
                                </div>
                            </template>
                            <!-- 商品类型对应的表格 -->
                            <el-table :data="dataForm.groupShopSkuList" style="width: 100%" stripe>
                                <el-table-column prop="id" label="skuId" width="60" />
                                <el-table-column prop="barCode" label="sku条形码" />
                                <el-table-column prop="title" label="类型名" />
                                <el-table-column prop="stock" label="库存" width="60" />
                                <el-table-column prop="price" label="现价/元" width="60" />
                                <el-table-column prop="skuGroupShopPrice" label="团购价格/元" />
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button type="primary" @click="handleUpdatePrice(scope.row)">更新</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-card>
                    </div>
                </div>
            </el-drawer>
        </div>
        <!-- 更新对话框 -->
        <el-dialog v-model="dialogTableVisible" title="更新团购价格" @close="handleCloseUpdateDialog">
            <el-form :model="priceForm">
                <el-form-item label="团购价格" :label-width="120">
                    <el-input-number v-model="priceForm.skuGroupShopPrice" controls-position="right" />
                </el-form-item>
                <el-form-item label="现价" :label-width="120">
                    {{ priceForm.price }}
                </el-form-item>
                <el-form-item label="sku类型名" :label-width="120">
                    {{ priceForm.title }}
                </el-form-item>
                <el-form-item :label-width="120">
                    <el-button @click="dialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdateSubmit">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import Pagination from "@/components/pagination/Pagination.vue";
import { computed, onMounted, reactive, ref } from "vue";
import { Search, Plus } from "@element-plus/icons-vue";
import { post } from "@/utils/http";
import { ClassGroupShop, ClassPagination, ClassGroupShopForm } from '#/index'
import { ElMessage, ElDrawer, ElMessageBox } from "element-plus";
import moment from "moment";
import { initObj } from '@/utils/index'
import type { FormInstance, FormRules } from 'element-plus'

// 添加修改表单节点
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    spuId: [{ required: true, message: '请选择商品', trigger: 'change' }],
    gmtStart: [{ required: true, message: '请选择起始时间', trigger: 'change' }],
    gmtEnd: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
})
//分页对象
const pagination = reactive(new ClassPagination())
//过滤对象
const filterGroupShop = reactive({
    id: undefined,
    spuName: undefined,
    status: undefined
})
//状态数据
const filterStatus = [
    { name: '冻结', value: 0 },
    { name: '激活', value: 1 }
]
//用于刷新多级联节点
const refresh = ref(0)
//正在加载 
const loading = ref(false)
//团购数据列表
const groupShopList = ref([{} as ClassGroupShop])
//商品属性
let dataForm = reactive(new ClassGroupShopForm())
//是否显示抽屉
const dialog = ref(false)
//更新对话框
const dialogTableVisible = ref(false)
//商品分类树
const spuBigTree = ref([])
//按钮节点
const refButton = ref()
//批量定价数据
const morePrice = ref(undefined)
//单个商品对话框
let priceForm = reactive({
    skuGroupShopPrice: undefined,
    price: 0,
    title: '',
    id: 0
})
//添加和删除对话框名称
const dialogName = ref('')
/**
 * 生命周期请求数据
 */
onMounted(() => {
    getGroupShop()
    getSpuBigTree()
})
//获取团购数据列表
function getGroupShop() {
    loading.value = true
    const data = { _gp: 'admin.groupshop', _mt: 'list', page: pagination.currentPage, limit: pagination.pageSize, ...filterGroupShop }
    post(data).then(res => {
        console.log(res)
        const { data, errmsg, errno } = res
        if (200 === errno) {
            const { items, total } = data
            groupShopList.value = items
            pagination.total = total
        } else {
            ElMessage.error(errmsg)
        }
        loading.value = false
    })
}
/**
 * 获取分类树
 */
function getSpuBigTree() {
    const data = { _gp: 'admin.product', _mt: 'getSpuBigTree' }
    post(data).then(res => {
        console.log(res)
        const { data, errmsg, errno } = res
        if (200 === errno) {
            spuBigTree.value = data
        } else {
            ElMessage.error(errmsg)
        }
    })
}

/**
 * 改变一页多少行,防止多次请求
 * @param value 一页多少行
 */
function handleSizeChange(value: number) {
    let tempCurrent = Math.ceil(pagination.total / value)
    if (tempCurrent < pagination.currentPage) {
        pagination.currentPage = tempCurrent
    }
    pagination.pageSize = value
    getGroupShop()
}

/**
 * 改变当前页
 * @param value 当前页数
 */
function handleCurrentChange(value: number) {
    pagination.currentPage = value
    getGroupShop()
}

/**
 * 打开添加抽屉
 */
function handleAddOpenDialog() {
    dialogName.value = "创建"
    dialog.value = true
    initObj(dataForm)
}
/**
 * 使用计算属性，计算dataForm表单数据
 */
let addGroup = computed(() => {
    let obj = new ClassGroupShopForm()
    Object.assign(obj, dataForm)
    obj.gmtStart = moment(obj.gmtStart).valueOf()
    obj.gmtEnd = moment(obj.gmtEnd).valueOf()
    return obj
})
/**
 * 改变商品获取对应的列表数据
 */
function handleChangeShop() {
    morePrice.value = undefined
    //如果商品id为空，清空列表数据
    if (!dataForm.spuId) {
        dataForm.groupShopSkuList = []
        refresh.value++
        return
    }
    const data = { _gp: 'admin.product', _mt: 'detail', spuId: dataForm.spuId }
    post(data).then(res => {
        const { data, errmsg, errno } = res
        if (res.data) {
            if (200 == errno) {
                data.skuList.forEach((item: { skuid: number; id: number; }) => {
                    item.skuid = item.id
                })
                dataForm.groupShopSkuList = data.skuList
            } else {
                ElMessage.error(errmsg)
            }
        }

    })
}
/**
 * 批量定价
 */
function handleMorePrice() {
    dataForm.groupShopSkuList.forEach((item) => {
        item.skuGroupShopPrice = morePrice.value

    })
    refButton.value.$el.click?.()
}
/**
 * 更新
 * @param row 当前行对象
 */
function handleUpdatePrice(row: TypeGroupShopSkuDTO) {
    dialogTableVisible.value = true
    Object.assign(priceForm, row)

}
/**
 * 更新提交
 */
function handleUpdateSubmit() {
    let index = dataForm.groupShopSkuList.findIndex(item => item.id == priceForm.id)
    if (index != -1) {
        dataForm.groupShopSkuList[index].skuGroupShopPrice = priceForm.skuGroupShopPrice
        dialogTableVisible.value = false
    }

}

/**
 * 创建
 */
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let mt = dialogName.value == "创建" ? 'create' : 'edit'
            const { gmtStart, gmtEnd, groupShopSkuList } = addGroup.value
            //判断起始时间不能大于结束时间
            if (gmtStart! > gmtEnd!) {
                ElMessage.error('起始时间不能大于结束时间')
                return
            }
            if (groupShopList) {
                let bol = groupShopSkuList.some(item => {
                    if (item.skuGroupShopPrice) {
                        return item?.skuGroupShopPrice > item.price
                    }
                })
                if (bol) {
                    ElMessage.error('团购金额不能大于现价')
                    return
                }
            }
            let obj = { ...addGroup.value, groupShopSkuList: JSON.stringify(dataForm.groupShopSkuList) }
            const data = { _gp: 'admin.groupshop', _mt: mt, ...obj }
            post(data).then(res => {
                console.log(res)
                const { data, errmsg, errno } = res
                if (200 === errno) {
                    ElMessage.success(dialogName.value + '成功')
                    dialog.value = false
                    getGroupShop()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 取消关闭抽屉
 */
function handleCancel() {
    dialog.value = false
}

/**
 * 关闭抽屉回调
 */
function handleCloseDialog() {
    morePrice.value = undefined
    ruleFormRef.value?.resetFields()
    initObj(dataForm)
}
/**
 * 关闭更新对话框
 */
function handleCloseUpdateDialog() {
    initObj(priceForm)
}
/**
 * 编辑
 * @param row 当前行对象
 */
function handleEdit(row: ClassGroupShop) {
    Object.assign(dataForm, row)
    //清空数组之后，进行拷贝
    dataForm.groupShopSkuList.length = 0;
    (row.groupShopSkuDTOList || []).forEach(item => {
        dataForm.groupShopSkuList.push(Object.assign({}, item))
    })
    dialog.value = true
    dialogName.value = "编辑"
}
/**
 * 删除
 * @param id 当前行id
 */
function handleDelete(id: number) {

    ElMessageBox.confirm(
        '是否删除该数据?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const data = { _gp: 'admin.groupshop', _mt: 'delete', id }
        post(data).then(res => {
            const { errno, errmsg } = res
            if (200 === errno) {
                ElMessage.success('删除成功')
            } else {
                ElMessage.error(errmsg)
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}
</script>
<style lang="less">
.page-filter {
    display: flex;
    height: 100%;
    overflow-x: hidden;
    flex-shrink: 0;

    &>.el-input {
        width: 200px;
        margin-right: 5px;
    }

    &>.el-select {
        margin-right: 5px;
    }
}

.in-table {
    border-collapse: collapse;
    border-spacing: 0;
    border: 1px solid #EBEEF5;
    border-right: 0;

    &>tr td {
        padding: 10px;
    }
}

.el-drawer {
    width: 50% !important;

    .el-drawer__body {
        padding: 0;

        .dialog-content {
            padding: 20px 0;
            border-top: #EBEEF5 1px solid;

            .shop-attribute {
                padding: 0 20px;
            }

            .shop-type {
                margin-top: 20px;
            }
        }
    }
}

.title-span {
    font-weight: 700;
    margin-bottom: 20px;
    display: block;
}

.el-date-editor {
    --el-date-editor-width: 180px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}</style>